// pages/home/subscribe/list/com/houseList/houseList.js
const app = getApp();
import api from "../../../../../../common/api"
import * as transferData from './../../../../../../models/transferData'
import * as filterConfig from './../../../../../../models/filter'
Component({
  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/
  },
  /**
   * 组件的属性列表
   */
  properties: {
    filterTime: {
      type: String,
      value: ''
    },
    infoType: {
      type: String,
      value: ''
    },
    salesType: {
      type: String,
      value: 'sales'
    },
    full: {
      type: Boolean,
      value: false,
    },
    cityCode: {
      type: String,
      value: ''
    },
    communityID: {
      type: String,
      value: ''
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    _listStartTime: null,
    isOpenCity: true,
    cityName: '',
    pageIndex: 0,
    pageSize: 20,
    houseList: [],
    hasMoreList: true,
    infoTypeCurrent: [],
    infoTypeOptions: [{
      value: '0',
      label: '新上'
    }, {
      value: '1',
      label: '带看'
    }, {
      value: '2',
      label: '调价'
    }, {
      value: '3',
      label: '下架'
    }],
    filterOptions: []
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function () {
      app.globalData.loginPromise.then(() => {
        this.initData()
        this.initFilterConfig()
        this.loadHouse()
      })
    },
    detached: function () {},
  },

  /**
   * 页面的生命周期
   */
  pageLifetimes: {
    show: function () {
      this.refreshMove()
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {

    initData() {
      const {
        infoType,
        filterTime
      } = this.data
      if (infoType) {
        this.setData({
          infoTypeCurrent: infoType.split(',')
        })
      }
      if (filterTime) {
        this.setData({
          ['filterOptions[0].filterValue']: {
            time: filterTime
          },
        })
      }
    },

    initFilterConfig() {
      const {
        salesType,
        filterOptions
      } = this.data
      let timeValue = '30'
      try {
        timeValue = filterOptions[0].filterValue.time ? filterOptions[0].filterValue.time : '30'
      } catch (error) {}
      this.setData({
        filterOptions: [{
          id: 'time',
          title: '时间',
          filterValue: {
            time: timeValue
          },
          filterOptions: [{
            id: 'time',
            title: '时间',
            single: filterConfig.rangeAddTime,
            defaultValue: '30'
          }],
        }, {
          id: 'price',
          title: '价格',
          filterValue: {},
          filterOptions: [{
            id: 'price',
            title: `价格区间(${salesType === 'sales' ? '万' : '元'})`,
            input: {},
            multi: salesType === 'sales' ? filterConfig.rangeSalesPrice : filterConfig.rangeRentPrice
          }],
        }, {
          id: 'area',
          title: '面积',
          filterValue: {},
          filterOptions: [{
            id: 'area',
            title: '建筑面积',
            input: {},
            multi: filterConfig.rangeArea
          }],
        }, {
          id: 'type',
          title: '户型',
          filterValue: {},
          filterOptions: [{
            id: 'type',
            title: '户型',
            multi: filterConfig.rangeHouseType
          }],
        }],
      })
    },

    onPageReachBottom() {
      this.loadHouse()
    },

    refreshMove() {
      if (transferData.getData('isRefreshSubscribe')) {
        transferData.resetData('isRefreshSubscribe')
        this.resetHouseData()
        this.loadHouse()
      }
    },

    onFilterChange(e) {
      let index = e.currentTarget.dataset.index
      let path = `filterOptions[${index}].filterValue`
      this.setData({
        [path]: e.detail.form,
      })
      if (index === 0) {
        this.triggerEvent('timeChange', e.detail.form.time)
      }
      this.resetHouseData()
      this.loadHouse()
    },

    resetHouseFilter() {
      this.setData({
        ['filterOptions[0].filterValue']: {
          time: '30'
        },
        ['filterOptions[1].filterValue']: {},
        ['filterOptions[2].filterValue']: {},
        ['filterOptions[3].filterValue']: {},
      })
    },

    resetHouseData() {
      this.setData({
        houseList: [],
        pageIndex: 0,
        hasMoreList: true,
      })
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
    },

    onInfoTypeChange(e) {
      this.setData({
        infoTypeCurrent: e.detail
      })
      this.resetHouseData()
      this.loadHouse()
    },

    loadHouse() {
      let t = this
      return new Promise((resolve, reject) => {
        let {
          pageIndex,
          pageSize,
          cityCode,
          hasMoreList,
          salesType,
          communityID,
          infoTypeCurrent,
          filterOptions
        } = t.data
        if (!hasMoreList) {
          resolve()
          return
        }
        wx.showLoading({
          title: '加载中...',
        })
        let currentIndex = pageIndex + 1
        if (currentIndex === 1) {
          t.data._listStartTime = new Date().getTime()
        }
        let extractResult = {}
        filterOptions.forEach(item => {
          extractResult[item.id] = item.filterValue[item.id]
        })
        let filter = filterConfig.parseFilter(extractResult)
        api.getExternalHouseList({
          intelligenceType: infoTypeCurrent.join(),
          areaList: filter.area,
          newExternalTime: filter.time,
          shiNumList: filter.type,
          priceList: filter.price,

          pageSize: pageSize,
          pageNum: currentIndex,
          cityCode: cityCode,
          hdResblockId: communityID,
          saleType: salesType.toUpperCase(),
          lastTime: t.data._listStartTime || null,
        }, (res) => {
          wx.hideLoading()
          if (res && res.data && res.data.isSuccess) {
            let result = res.data.content || {}
            let list = result.list || []
            let maxIndex = result.pages
            let formatList = list.map(item => {
              let price = item.price || 0
              let priceTrend = item.priceTrend || 0
              return {
                houseLinkUrl: item.externalInfoUrl || '',
                houseCommunityID: item.communityId || '',
                houseCommunityName: item.communityName || '',
                houseTitle: item.title || '',
                houseDescribe: item.contentDescribe || '',
                houseType: item.saleType || '',
                houseImg: item.fileUrl || '',
                houseRoom: item.shi || 0,
                houseHall: item.ting || 0,
                houseArea: item.buildingSize || '',
                houseAddTime: item.releaseDateStr || '',
                housePrice: item.saleType === "SALES" ? price / 10000 : price,
                houseSource: item.externalName || '',
                houseAreaPrice: item.unitPriceStr ? item.unitPriceStr.replace(',', '') : '',
                houseIsMove: item.isMoveHouse || false,
                houseFocusNum: item.focusValue || 0,
                housePriceTrend: item.saleType === "SALES" ? priceTrend / 10000 : priceTrend,
                houseIsSoldOut: item.isSoldOut || false,
                houseMonthLookValue: item.monthLookValue || 0
              }
            })
            if (currentIndex === 1) {
              t.data.houseList = [...formatList]
            } else {
              t.data.houseList.push(...formatList)
            }
            t.setData({
              pageIndex: currentIndex,
              hasMoreList: currentIndex >= maxIndex ? false : true,
              houseList: t.data.houseList
            })
            resolve()
          } else {
            if (res.data.errorCode === '30003') {
              t.setData({
                isOpenCity: false
              })
              resolve()
            } else {
              reject()
            }
          }
        }, () => {
          reject()
          wx.hideLoading()
        });
      })
    },

  }
})